import path from "node:path";
import { RunnerSpec, TaskHandler } from "../types";
import { resolvePath, ensureDir } from "../utils";
import { readBlueprint } from "../../../tools/data-processor";

async function readTokens(tokensPath: string): Promise<any> {
  const { loadStructuredData } = await import("../../../tools/data-processor");
  return loadStructuredData(tokensPath);
}

export const summaryGenerateTask: TaskHandler = async (spec) => {
  const tokensRelative = spec.figma?.tokensPath ?? spec.output?.tokens ?? path.join(spec.output?.dir ?? "figma", "tokens.json");
  const summaryRelative = spec.figma?.summaryPath ?? spec.output?.summary ?? path.join(spec.output?.dir ?? "figma", "summary.md");
  const tokensPath = resolvePath(tokensRelative);
  const summaryPath = resolvePath(summaryRelative);
  await ensureDir(path.dirname(summaryPath));

  const tokens = await readTokens(tokensPath);
  const blueprintPath = spec.blueprint?.path;
  const designIntent = blueprintPath ? await readBlueprint(blueprintPath, ["designIntent"]) : {};

  const sections = [
    "## Colors",
    JSON.stringify(tokens.colors ?? [], null, 2),
    "## Typography",
    JSON.stringify(tokens.typography ?? [], null, 2),
    "## Spacing",
    JSON.stringify(tokens.spacing ?? [], null, 2),
    "## Design Intent",
    JSON.stringify(designIntent, null, 2),
  ].join("\n\n");

  await fsWrite(summaryPath, sections);

  return {
    summary: `Generated summary at ${summaryRelative}`,
    outputPaths: { summary: summaryRelative },
  };
};

async function fsWrite(target: string, content: string) {
  const fs = await import("node:fs/promises");
  await fs.writeFile(target, content, "utf-8");
}
